package com.aspirecn.core.commons;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang.math.RandomUtils;

import com.aspirecn.core.ShareCommon;
import com.aspirecn.core.object.ImageQuestion;

/**
 * 原生成校验码和回答问题图片
 * @author wangxinning
 *
 */
public class PhotoUtils {

	/**
	 * 获取随机数字图片，返回图片内容
	 * 
	 * @param width
	 * @param height
	 * @param codeCount
	 * @param os
	 * @return
	 * @throws IOException
	 */
	public static String getRandomCode(int width, int height, int codeCount,
			OutputStream os) throws IOException {
		int x = width / (codeCount + 1);
		int fontHeight = height - 2;
		int codeY = height - 4;

		BufferedImage buffImg = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = buffImg.createGraphics();

		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);

		Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
		g.setFont(font);

		g.setColor(Color.BLACK);
		g.drawRect(0, 0, width - 1, height - 1);

		g.setColor(Color.BLACK);
		for (int i = 0; i < 14; i++) {
			int xx = RandomUtils.nextInt(width);
			int y = RandomUtils.nextInt(height);
			int xl = RandomUtils.nextInt(12);
			int yl = RandomUtils.nextInt(12);
			g.drawLine(xx, y, xx + xl, y + yl);
		}

		String randomCode = "";
		int red = 0, green = 0, blue = 0;

		for (int i = 0; i < codeCount; i++) {
			String strRand = RandomStringUtils.randomNumeric(1);
			
			red = RandomUtils.nextInt(255);
			green = RandomUtils.nextInt(255);
			blue = RandomUtils.nextInt(255);

			g.setColor(new Color(red, green, blue));
			g.drawString(strRand, (i + 1) * x, codeY);

			randomCode += strRand;
		}

		ImageIO.write(buffImg, "jpeg", os);

		return randomCode;
	}

	// type 0正常 1小
	private static String getResult(OutputStream os, int type) {

		// 随机获取一条数据
		ImageQuestion imageQuestion = ShareCommon.getInstance()
				.getImageQuestionCache().getRandom();

		if (imageQuestion != null) {
			// 读取资源图片
			InputStream is = null;
			try {
				is = FileUtils.openInputStream(new File(imageQuestion
						.getFilename()));
			} catch (IOException e1) {
				e1.printStackTrace();
				return null;
			}

			// 获取结果数组，一个正确数据，3个错误数据
			String[] resultArray = makeResultArray(
					imageQuestion.getYesResult(), imageQuestion.getNoResult());
			String ret = StringUtils.substringBefore(resultArray[0], ".");

			// 图片流输出
			try {
				if (type == 0) {
					outImg(luan(resultArray), is, os);
				} else if (type == 1) {
					outImgSmall(luan(resultArray), is, os);
				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				IOUtils.closeQuietly(is);
			}

			return ret;

		} else {
			return null;
		}
	}

	public static String getResult(OutputStream os) {

		return getResult(os, 0);
	}

	public static String getResultSmall(OutputStream os) {

		return getResult(os, 1);
	}

	private static String[] makeResultArray(String yesStr, String noStr) {
		String[] strArray = new String[4];

		String[] questionArray = getRandomChar(4);
		
		String[] yesArray = StringUtils.split(yesStr, ",");
		
		
		strArray[0] = questionArray[0] + "."
				+ yesArray[RandomUtils.nextInt(yesArray.length)];
		String[] noArray = StringUtils.split(noStr, ",");		
		String src = noArray[RandomUtils.nextInt(noArray.length)];
		strArray[1] = questionArray[1] + "." + src;
		noArray = (String[]) ArrayUtils.removeElement(noArray, src);
		src = noArray[RandomUtils.nextInt(noArray.length)];
		strArray[2] = questionArray[2] + "." + src;
		noArray = (String[]) ArrayUtils.removeElement(noArray, src);
		src = noArray[RandomUtils.nextInt(noArray.length)];
		strArray[3] = questionArray[3] + "." + src;

		return strArray;
	}
	
	//不重复，大写
	private static String[] getRandomChar( int count )
	{
		String[] ret = null;
		
		while( true )
		{
			String s = StringUtils.upperCase(RandomStringUtils.randomAlphabetic(1));
			
			if( !ArrayUtils.contains(ret, s) )
			{
				ret = ArrayUtils.add(ret, s);
			}
			
			int length = ArrayUtils.getLength(ret);
			if( length >= count || length >= 26 )
			{
				break;
			}
		}
		
		return ret;
	}
	

	private static void outImg(String[] result, InputStream is, OutputStream os)
			throws Exception {
		int fontsize = 13;
		int maxlength = 135;
		int maxwidth = 40;

		int x = 2;
		int y = 15;
		int size = 12;

		BufferedImage buffImage = ImageIO.read(is);
		Graphics g = buffImage.getGraphics();
		Font font = new Font("宋体", Font.PLAIN, size);
		g.setFont(font);
		g.setColor(Color.BLACK);
		g.drawString(result[0], x, y);
		g.drawString(result[1], x
				+ (maxlength - (result[1].length() - 1) * fontsize), y);
		g.drawString(result[2], x, y + maxwidth / 2);
		g.drawString(result[3], x
				+ (maxlength - (result[3].length() - 1) * fontsize), y
				+ maxwidth / 2);
		ImageIO.write(buffImage, "jpg", os);

	}

	private static void outImgSmall(String[] result, InputStream is,
			OutputStream os) throws Exception {
		int fontsize = 12;
		int maxlength = 122;
		int maxwidth = 36;

		int x = 2;
		int y = 15;
		int size = 11;

		BufferedImage buffImage = ImageIO.read(is);

		double d = (double) 1.1;

		int width = (int) (buffImage.getWidth() / d);
		int height = (int) (buffImage.getHeight() / d);

		Image newImg = buffImage.getScaledInstance(width, height,
				Image.SCALE_AREA_AVERAGING);
		buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		buffImage.getGraphics().drawImage(newImg, 0, 0, width, height, null);

		Graphics g = buffImage.getGraphics();
		Font font = new Font("宋体", Font.PLAIN, size);
		g.setFont(font);
		g.setColor(Color.BLACK);
		g.drawString(result[0], x, y);
		g.drawString(result[1], x
				+ (maxlength - (result[1].length() - 1) * fontsize), y);
		g.drawString(result[2], x, y + maxwidth / 2);
		g.drawString(result[3], x
				+ (maxlength - (result[3].length() - 1) * fontsize), y
				+ maxwidth / 2);
		ImageIO.write(buffImage, "jpg", os);

	}

	/**
	 * 数组乱序，为了打乱答案的顺序
	 * 
	 * @param args
	 * @return
	 */
	private static String[] luan(String[] args) {
		String[] ret = new String[0];

		while (args != null && args.length > 0) {
			String temp = args[RandomUtils.nextInt(args.length)];
			if (!ArrayUtils.contains(ret, temp)) {
				ret = (String[]) ArrayUtils.add(ret, temp);
				args = (String[]) ArrayUtils.removeElement(args, temp);
			}
		}

		return ret;
	}

	
	public static void main(String[] args) throws IOException {

		FileOutputStream os = new FileOutputStream("F:/444.jpg");
		System.out.println(PhotoUtils.getRandomCode(400, 150, 4, os));
//		 for (int i = 0; i < 2000; i++) {
//		 os = new FileOutputStream("F:/aaa/" + i + ".jpg");
//		 System.out.println(PhotoUtils.getResult(os));
//		 IOUtils.closeQuietly(os);
//		 }
//
//		return;
		
		System.out.println( RandomStringUtils.randomNumeric(1) );
	}
}
